package com.wh.message.mongo.service.impl;

import com.wh.message.mongo.service.MongoMessageService;
import com.wh.message.mongo.util.MongoUtil;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;

/**
 * MONGODB数据库业务接口实现层
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.mongo.service.impl
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class MongoMessageServiceImpl implements MongoMessageService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String dataBase;

    public String getDataBase() {
        return dataBase;
    }

    public void setDataBase(String dataBase) {
        this.dataBase = dataBase;
    }

    /**
     * 添加数据到对应表中
     * @param tableName 数据库名
     * @param data      存放数据
     */
    @Override
    public void addObj(String tableName, Object ... data) {
        try {
            logger.info("MONGODB-->>tableName数据库-->>开始");
            logger.info("MONGODB-->>tableName数据库-->>tableName = {}", tableName);
            logger.info("MONGODB-->>tableName数据库-->>data = {}", JSONArray.fromObject(data).toString());
            //获取数据库连接
            MongoDatabase mongoDatabase = MongoUtil.initDb(dataBase);
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(tableName);
            Document document = new Document();
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
                @Override
                public boolean apply(Object arg0, String arg1, Object arg2) {
                    return false;
                }
            });
            for (int i = 0; i < data.length; i++){
                Object object = data[i];
                if(null != object){
                    try {
                        if(object instanceof  JSONObject) {
                            logger.info("MONGODB-->>tableName数据库-->>解析字符串-->>object = {}", JSONObject.fromObject(object).toString());
                            //将传入的值封装成对应的json
                            JSONObject jsonObject = JSONObject.fromObject(object, jsonConfig);
                            if (null != jsonObject) {
                                Iterator iterator = jsonObject.keys();
                                while (iterator.hasNext()) {
                                    Object key = iterator.next();
                                    if (null != jsonObject.get(key) && !"null".equals(jsonObject.get(key).toString())) {
                                        document.append(key.toString(), jsonObject.get(key));
                                    } else {
                                        document.append(key.toString(), null);
                                    }
                                }
                            }
                        }else if(object instanceof  JSONArray){
                            logger.info("MONGODB-->>tableName数据库-->>解析字符串-->>object = {}", JSONArray.fromObject(object).toString());
                            document.append("data_" + (i + 1), object.toString());
                        }
                    }catch (Exception ex ){
                        ex.printStackTrace();
                        logger.error("MONGODB-->>tableName数据库-->>异常信息：" +  ex.getMessage());
                    }
                }
            }
            if(document.size() > 0) {
                mongoCollection.insertOne(document);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("MONGODB-->>tableName数据库-->>出现异常：MONGODB数据库已挂：" +  e.getMessage());
        }
            logger.info("MONGODB-->>tableName数据库-->>结束");
    }


}
